using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace VideoAutoGenerator.Core
{
    /// <summary>
    /// 配置管理器，用于读取和保存config.json配置文件
    /// </summary>
    public class ConfigManager
    {
        private readonly string _configPath;
        private JObject _config = new JObject(); // 初始化为避免警告

        // Singleton instance
        private static ConfigManager _instance;
        public static ConfigManager Instance { get { return _instance ?? (_instance = new ConfigManager()); } }

        public ConfigManager(string configPath = null)
        {
            _configPath = configPath ?? GetDefaultConfigPath();
            System.Console.WriteLine("ConfigManager: " + _configPath);
            LoadConfig();
        }

        /// <summary>
        /// 获取默认配置文件路径
        /// </summary>
        private string GetDefaultConfigPath()
        {
            // 获取当前应用程序的目录
            string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
            // 导航到配置文件目录（相对于应用程序目录）
            string configPath = Path.Combine(appDirectory, @"..\..\..\..\..\", "config.json");
            return Path.GetFullPath(configPath);
        }

        /// <summary>
        /// 获取配置文件路径
        /// </summary>
        public string ConfigPath { get { return _configPath; } }

        /// <summary>
        /// 从文件加载配置
        /// </summary>
        private void LoadConfig()
        {
            try
            {
                if (File.Exists(_configPath))
                {
                    string json = File.ReadAllText(_configPath);
                    _config = JObject.Parse(json);
                }
                else
                {
                    // 如果配置文件不存在，创建默认配置
                    CreateDefaultConfig();
                }
            }
            catch (Exception)
            {
                // 如果解析失败，创建默认配置
                CreateDefaultConfig();
            }
        }

        /// <summary>
        /// 创建默认配置
        /// </summary>
        private void CreateDefaultConfig()
        {
            _config = new JObject
            {
                ["title"] = "奥巴马演讲\n(2)",
                ["inputDirDat"] = "./input/dat",
                ["inputDirMp3"] = "./input/mp3",
                ["inputStartVoice"] = "./input/voice/tada.wav",
                ["inputDirImages"] = "./temp/imgs",
                ["inputDirVideos"] = "./input/videos",
                ["outputDirSrt"] = "./temp/srt",
                ["outputDirVideo"] = "./output/videos",
                ["mediaStore"] = "./mediaStore",
                ["encodeFormat"] = "h264_nvenc",
                ["useTransitionEffect"] = false,
                ["encodeFormat-Lib264"] = "libx264--不支持NVIDIA的计算机上使用libx264,否则使用h264_nvenc",
                ["pexelsApiKey"] = "kwITE2AN3q83bYfxyLLDtpA8H0Rh4jFTh6GYQ5AJhMSJiEPzp22X3yhJ",
                ["projectSettings"] = new JObject
                {
                    ["imageDuration"] = 3000,
                    ["defaultAudioDuration"] = 60000,
                    ["videoWidth"] = 1080,
                    ["videoHeight"] = 1920,
                    ["firstLineFontStyle"] = new JObject
                    {
                        ["fontSize"] = 128,
                        ["color"] = "yellow",
                        ["fontFamily"] = "Microsoft YaHei",
                        ["fontStyle"] = "normal"
                    },
                    ["secondLineFontStyle"] = new JObject
                    {
                        ["fontSize"] = 72,
                        ["color"] = "red",
                        ["fontFamily"] = "Microsoft YaHei",
                        ["fontStyle"] = "italic"
                    },
                    ["textStyles"] = new JObject
                    {
                        ["fontSize"] = 48,
                        ["fontFamily"] = "Arial",
                        ["color"] = "#FF0000",
                        ["backgroundColor"] = "#00000080",
                        ["highlightBackgroundColor"] = "#000000"
                    },
                    ["wordStyles"] = new JObject
                    {
                        ["word"] = new JObject
                        {
                            ["fontSize"] = 48,
                            ["color"] = "#00FF00",
                            ["bold"] = 1,
                            ["italic"] = 0,
                            ["outlineColor"] = "#FF0000",
                            ["alignment"] = 7
                        },
                        ["phonetic"] = new JObject
                        {
                            ["fontSize"] = 36,
                            ["color"] = "#FFFF00",
                            ["bold"] = 0,
                            ["italic"] = 1,
                            ["alignment"] = 8
                        },
                        ["translation"] = new JObject
                        {
                            ["fontSize"] = 24,
                            ["color"] = "#00FFFF",
                            ["bold"] = 0,
                            ["italic"] = 0,
                            ["alignment"] = 8
                        }
                    }
                },
                ["waveform"] = new JObject
                {
                    ["enabled"] = true,
                    ["height"] = 100,
                    ["color"] = "00ff00",
                    ["position"] = "bottom"
                },
                ["ffmpeg"] = new JObject
                {
                    ["path"] = "E:\\Words\\vsr\\resources\\backend\\ffmpeg\\win_x64\\ffmpeg.exe"
                }
            };
        }

        /// <summary>
        /// 保存配置到文件
        /// </summary>
        public void SaveConfig()
        {
            try
            {
                string json = JsonConvert.SerializeObject(_config, Formatting.Indented);
                File.WriteAllText(_configPath, json);
            }
            catch (Exception ex)
            {
                throw new Exception($"保存配置文件失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 获取配置值
        /// </summary>
        /// <param name="key">配置键</param>
        /// <returns>配置值</returns>
        public JToken GetValue(string key)
        {
            return _config.SelectToken(key);
        }

        /// <summary>
        /// 设置配置值
        /// </summary>
        /// <param name="key">配置键</param>
        /// <param name="value">配置值</param>
        public void SetValue(string key, JToken value)
        {
            var token = _config.SelectToken(key);
            if (token != null)
            {
                var parent = token.Parent;
                if (parent is JProperty property)
                {
                    property.Value = value;
                }
                else
                {
                    // 如果token是JProperty本身
                    token.Replace(value);
                }
            }
            else
            {
                // 如果键不存在，创建新的
                var paths = key.Split('.');
                JToken current = _config;
                
                for (int i = 0; i < paths.Length - 1; i++)
                {
                    var next = current[paths[i]];
                    if (next == null)
                    {
                        var newObj = new JObject();
                        ((JObject)current)[paths[i]] = newObj;
                        current = newObj;
                    }
                    else
                    {
                        current = next;
                    }
                }
                
                ((JObject)current)[paths[paths.Length - 1]] = value;
            }
        }

        /// <summary>
        /// 获取字符串配置值
        /// </summary>
        /// <param name="key">配置键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值</returns>
        public string GetString(string key, string defaultValue = "")
        {
            var token = GetValue(key);
            return token != null ? token.ToString() : defaultValue;
        }

        /// <summary>
        /// 获取整数配置值
        /// </summary>
        /// <param name="key">配置键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值</returns>
        public int GetInt(string key, int defaultValue = 0)
        {
            var token = GetValue(key);
            return token != null ? token.ToObject<int>() : defaultValue;
        }

        /// <summary>
        /// 获取布尔配置值
        /// </summary>
        /// <param name="key">配置键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值</returns>
        public bool GetBool(string key, bool defaultValue = false)
        {
            var token = GetValue(key);
            return token != null ? token.ToObject<bool>() : defaultValue;
        }

        /// <summary>
        /// 获取对象配置值
        /// </summary>
        /// <param name="key">配置键</param>
        /// <returns>配置对象</returns>
        public JObject GetObject(string key)
        {
            var token = GetValue(key);
            return token as JObject;
        }

        /// <summary>
        /// 重新加载配置文件
        /// </summary>
        public void ReloadConfig()
        {
            LoadConfig();
        }

        /// <summary>
        /// 获取完整的配置对象
        /// </summary>
        /// <returns>配置对象</returns>
        public JObject GetConfig()
        {
            return _config;
        }
    }
}